<?php
/**
 * Plugin to setup navigation bar.
 *
 * @category Zend
 * @package Navigation
 * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc.
 * @version $Id$
 * @link http://framework.zend.com
 * @since Available since release 1.0
 */

class Disputeo_Controller_Plugin_Navigation extends Zend_Controller_Plugin_Abstract
{
    /**
     * @var Zend_Navigation
     */
    protected $_navigation;
    
    /**
     * @var Zend_Acl
     */
    protected $_acl;
    
    /**
     * @var Zend_View_Abstract
     */
    protected $_view;
    
    /**
     * Setup links and active nav bar item
     * 
     * @param Zend_Controller_Request_Abstract $request 
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $this->_view = Zend_Controller_Front::getInstance()
            ->getParam('bootstrap')
            ->getResource('layout')
            ->getView();
        
        $this->_acl = Zend_Registry::get('acl');
        $this->_navigation = new Zend_Navigation($this->_getConfig());
        
        $this->_checkAccess();
        $this->_setActive($request->getControllerName() . '-' . $request->getActionName());
        
    }
    
    /**
     * Get config data from cache or XML file
     * 
     * @return Array
     */
    protected function _getConfig()
    {
        $configPath = APPLICATION_PATH . '/configs/navigation.xml';
        $config = Disputeo_Cache::classCache(
            new Zend_Config_Xml($configPath, 'nav')
        );
        
        return $config->toArray();
    }
    
    /**
     * Remove pages user is denied access to
     */
    protected function _checkAccess()
    {
        $role = Disputeo_Session::getSession()->usertype;
        
        foreach ($this->_navigation as $page) {
            if ($page->resource && ! $this->_acl->isAllowed($role, $page->resource)) {
                $this->_navigation->removePage($page);
            }
        }
    }
    
    /**
     * Set ul class and mark li as active
     * 
     * @param string $id 
     */
    protected function _setActive($id)
    {
        $menu = $this->_view->navigation($this->_navigation)
            ->menu()
            ->setUlClass('nav');
        
        $page = $menu->findById($id);
        if ($page) {
            $page->setActive(true);
            if (! $page->visible) {
                $page->getParent()->current()->setActive(true);
            }
        }
    }
}